using System;
using Combat;
using UnityEngine;
using Utils;

namespace Locomotion
{
    public class Mover : MonoBehaviour
    {
        public bool IsMoving => _moveDirection != Vector2.zero;
        
        public Vector2 MoveDirection => _moveDirection;
        
        [SerializeField] private float moveSpeed = 4f;
        
        private bool IsFrozen => _freezeTimer.IsActive;
        
        private Timer _freezeTimer;

        private Health _health;

        private Vector2 _moveDirection;
        private Vector2 _recoilForce = Vector2.zero;


        private void Awake()
        {
            _health = GetComponent<Health>();
            
            _health.Died += Health_Died;
            _health.Hit += Health_Hit;

            _freezeTimer = new Timer(0f, () => _recoilForce = Vector2.zero);
        }

        private void Update()
        {
            _freezeTimer.Tick();
            
            transform.Translate((_moveDirection + _recoilForce) * (moveSpeed * Time.deltaTime));
        }

        public void Move(Vector2 moveDirection)
        {
            _moveDirection = moveDirection;
        }

        public void StopMoving()
        {
            _moveDirection = Vector2.zero;
        }

        public void Knock(Vector2 direction, float force, float freezeTime)
        {
            _freezeTimer.Reset(freezeTime);
            
            _recoilForce = direction * force;
        }
        
        private void Health_Died()
        {
            StopMoving();
        }
        
        private void Health_Hit(Vector2 hitDirection)
        {
            Knock(hitDirection, 6f, 0.1f);
        }
    }
}